'use strict';

/** @type {import('sequelize-cli').Migration} */
module.exports = {
  async up(queryInterface, Sequelize) {
    /**
     * Add altering commands here.
     */
    await queryInterface.createTable('sys_dict_items', {
      id: {
        type: Sequelize.BIGINT,
        primaryKey: true,
        comment: '字典项ID',
      },
      dict_type_id: {
        type: Sequelize.BIGINT,
        allowNull: false,
        comment: '字典类型ID',
        references: {
          model: 'sys_dict_types',
          key: 'id',
        },
        onUpdate: 'CASCADE',
        onDelete: 'CASCADE',
      },
      label: {
        type: Sequelize.STRING(50),
        allowNull: false,
        comment: '字典项标签',
      },
      value: {
        type: Sequelize.STRING(50),
        allowNull: false,
        comment: '字典项值',
      },
      sort: {
        type: Sequelize.INTEGER,
        allowNull: false,
        defaultValue: 0,
        comment: '排序号',
      },
      status: {
        type: Sequelize.BOOLEAN,
        defaultValue: true,
        comment: '状态: true-启用, false-禁用',
      },
      create_time: {
        type: Sequelize.DATE,
        allowNull: false,
        defaultValue: Sequelize.NOW,
        comment: '创建时间',
      },
      update_time: {
        type: Sequelize.DATE,
        allowNull: false,
        defaultValue: Sequelize.NOW,
        onUpdate: Sequelize.NOW,
        comment: '更新时间',
      },
    });

    // 添加索引，提高查询效率
    await queryInterface.addIndex('sys_dict_items', [ 'dict_type_id' ]);
    await queryInterface.addIndex('sys_dict_items', [ 'dict_type_id', 'value' ], {
      unique: true,
      name: 'uk_dict_type_value',
    });
  },

  async down(queryInterface, Sequelize) {
    /**
     * Add reverting commands here.
     */
    // 先删除外键约束
    await queryInterface.removeConstraint('sys_dict_items', 'sys_dict_items_ibfk_1');
    // 再删除索引
    await queryInterface.removeIndex('sys_dict_items', 'uk_dict_type_value');
    await queryInterface.removeIndex('sys_dict_items', 'sys_dict_items_dict_type_id');
    // 最后删除表
    await queryInterface.dropTable('sys_dict_items');
  },
};
